package com.szholly.plug.safe.core;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.szholly.utils.session.SessionFactory;
import com.szholly.utils.session.provider.ISessionProvider;
import com.szholly.data.general.IUpdateMap;
import com.szholly.data.general.UpdateMap;
import com.szholly.plug.safe.entity.user.UserEntity;
import com.szholly.plug.safe.entity.user.UserService;


@Controller
public class SafeController {
	/**
	 * 获取当前的系统表集
	 * 
	 * @param req
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/safe/password")
	public void savePassword(
			@RequestParam("oldPW")String oldPW,
			@RequestParam("newPW")String newPW,
			@RequestParam("rnewPW")String rnewPW,
			HttpServletResponse response)
			throws IOException {
		ISessionProvider session = SessionFactory.getSession();
		UserEntity userEntity = (UserEntity) session
				.getObject(ISessionProvider.UserEntity);
		if(userEntity==null){
			getError(response, "请先登录！");
			return;
		}
		
		if(!userEntity.getPassword().equals(oldPW)){
			getError(response, "旧密码输入错误！");
			return;
		}
		
		if(!newPW.equals(rnewPW)){
			getError(response, "两次新密码输入不一至！");
			return;
		}
		
		IUpdateMap updateMap = new UpdateMap();
		updateMap.getWhereMap().put(UserEntity.FIELD_USERID, userEntity.getUserID());
		updateMap.getSetMap().put(UserEntity.FIELD_C_PWD, newPW);
		UserService.getSingleRef().update(updateMap);
		
		userEntity.setPassword(newPW);
	}
	
	private void getError(HttpServletResponse response, String msg) {
		// 向浏览器发送一个响应头，设置浏览器的解码方式为UTF-8
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		try {
			OutputStream stream = response.getOutputStream();
			stream.write(msg.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}